package com.example.demo.services;

import com.example.demo.entity.RoleEntity;
import com.example.demo.entity.UserEntity;
import com.example.demo.jpa.RoleJpa;
import com.example.demo.jpa.UserJpa;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author rqian
 */
public class CustomUserServiceIml implements CustomUserService {
    @Autowired
    private UserJpa mUserJpa;
    @Autowired
    private RoleJpa mRoleJpa;



    @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        UserEntity user = mUserJpa.findUserEntityByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("Username is not exist.");
        }
        return user;
    }



    @Override
    public UserEntity saveUser(final UserEntity userEntity, final String role) {
        UserEntity savedUser = null;
        userEntity.setEncodePassword(userEntity.getPassword());
        RoleEntity roleEntity = mRoleJpa.findRoleEntityByRoleName(role);
        if (null != roleEntity) {
            List<RoleEntity> roles = new ArrayList<>();
            roles.add(roleEntity);
            userEntity.setRoles(roles);
            savedUser = mUserJpa.save(userEntity);
        }
        return savedUser;
    }
}
